# $Id: device.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
import threading

from django.conf import settings

from djanet.lib.exception import ConfigCopyError
from djanet.tools.lib import ConfigCopy

class DeviceBackup(threading.Thread):
   def __init__(self, Queue, Sleep):
      super(DeviceBackup, self).__init__()
      self._err = exception.AppError()
      self._type = None
      self._queue = Queue
      self._errmesg = None
      self._configFile = None
      self.device = None
      self._sleep = Sleep

   def __getattr__(self, name):
      retval = None
      if isinstance(name, (str, unicode)):
         if name.lower() == "config":
            retval = self._getconfig()
         elif name.lower() == "error":
            retval = self._errmesg

      return retval

   def devtype(self):
      if self.device.sysdescription.find("IOS") >= 0:
         self._type = "IOS"
      elif self.device.sysdescription.find("Adaptive Security Appliance") >= 0:
         self._type = "ASA"
      elif self.device.sysdescription.find("NX-OS") >= 0:
         self._type = "NXOS"
      elif self.device.sysdescription.find("Firewall Services Module") >= 0:
         self._type = "FWSM"

   def snmpbackup(self, device):
      retval = 0
      if self._type == "IOS":
         backup = None
         try:
            backup = ConfigCopy.ConfigCopy(str(device), self._type, self._sleep)
         except exception.ConfigCopyError as err:
            self._errmesg = err.message
         else:
            try:
               backup.tftpInit()
               retval = backup.GetConfig(True)
               if retval:
                  self._configfile = backup.GetConfigFile()
            except exception.ConfigCopyError as err:
               self._errmesg = err.message
         finally:
            if backup:
               backup.Close()

      return retval

   def sshbackup(self, device):
      retval = 0
      if self._type in ("ASA", "FWSM", "NXOS", "IOS") and device:
         backup = None
         try:
            backup = ConfigCopy.ConfigCopy(str(device), self._type, self._sleep)
         except exception.ConfigCopyError as err:
            self._errmesg = err.message
         else:
            try:
               backup.tftpInit()
               retval = backup.GetConfig(False)
               if retval:
                  self._configFile = backup.GetConfigFile()
            except exception.ConfigCopyError as err:
               self._errmesg = err.message
         finally:
            if backup:
               backup.Close()

      return retval

   def _getconfig(self):
      retval = None
      if not self._errmesg:
         retval = self._configFile

      return retval

   def __str__(self):
      return str(self.device).encode('utf-8')

   def __int__(self):
      retval = 0
      if self.device:
         retval = self.device.id

      return retval

   def run(self):
      self.device = self._queue.get()
      self.setName(str(self.device))
      if self.device:
         self.devtype()
         if self.snmpbackup(self.device) or self.sshbackup(self.device):
            self._errmesg = None
         else:
            self._configFile = None

      self._queue.task_done()
